package service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
)

// 获取用户信息
type UserJson struct {
	Aid int `json:"aid"`
	Mid int `json:"mid"`
}
type UserData struct {
	ID              int             `json:"id"`
	Aid             int             `json:"aid"`                        //商户id
	Nickname        string          `json:"nickname"`                   //昵称
	Headimg         string          `json:"headimg"`                    //头像
	Sex             string          `json:"sex"`                        //性别
	Realname        string          `json:"realname"`                   //姓名
	Tel             string          `json:"tel"`                        //手机号
	Birthday        string          `json:"birthday"`                   //生日
	Money           decimal.Decimal `json:"money"`                      //余额
	Commission      decimal.Decimal `json:"commission"`                 //佣金余额
	Totalcommission decimal.Decimal `json:"totalcommission"`            //总计获得的佣金
	Score           int             `gorm:"type:int(11);" json:"score"` //积分
	Levelid         int             `json:"levelid"`                    //会员等级ID
	LevelName       string          `json:"level_name"`                 //会员等级
	Province        string          `json:"province"`                   //省份
	City            string          `json:"city"`                       //城市
	Area            string          `json:"area"`                       //区域
	Address         string          `json:"address"`                    //街道
	Latitude        string          `json:"latitude"`                   //纬度
	Longitude       string          `json:"longitude"`                  //经度
	Coupon          int64           `json:"coupon"`                     //优惠券数量
	KeFuUrl         string          `json:"ke_fu_url"`                  //
	MyRecharge      decimal.Decimal `json:"my_recharge"`                //个人充值
	Give            decimal.Decimal `json:"give"`                       //平台赠送
}
type RechargeReturn struct {
	MyRecharge decimal.Decimal `json:"my_recharge"` //个人充值
	Give       decimal.Decimal `json:"give"`        //平台赠送
}

// 获取用户详情
func UserInfo(c *gin.Context) {
	var jsonData UserJson
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var list UserData
	selectData := "m_member.id,m_member.levelid,m_member_level.name as level_name,m_member.money,m_member.totalcommission,m_member.commission" +
		",m_member.score,m_member.nickname,m_member.headimg,m_member.sex,m_member.realname,m_member.tel,m_member.birthday,m_member.province" +
		",m_member.city,m_member.area,m_member.address,m_member.latitude,m_member.longitude"
	err = models.DB.Table("m_member").Select(selectData).Joins("left join m_member_level on m_member_level.id=m_member.levelid").Where("m_member.id=? AND m_member.aid=?", jsonData.Mid, jsonData.Aid).First(&list).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	//获取该用户优惠券的数量
	var couponData []models.MCouponRecord
	var coupon int64
	err = models.DB.Model(new(models.MCouponRecord)).Where("mid=? AND aid=? AND status=?", jsonData.Mid, jsonData.Aid, 0).Count(&coupon).Find(&couponData).Error
	if err != nil {
		define.Response.ResultFail(c, 10002, define.JsonDataX, "")
		return
	}
	list.Coupon = coupon
	var adminData models.MAdminSet
	err = models.DB.Model(new(models.MAdminSet)).Where("aid=?", jsonData.Aid).First(&adminData).Error
	if err != nil {
		define.Response.ResultFail(c, 10002, define.JsonDataX, "")
		return
	}
	list.KeFuUrl = adminData.Kfurl
	//统计用户充值金额与平台赠送
	var rechargeOrderData models.MRechargeOrder
	err = models.DB.Table("m_recharge_order").Select("SUM(m_recharge_order.money) as money,SUM(m_recharge_order.give) as give").Where("m_recharge_order.mid=? AND m_recharge_order.status=?", jsonData.Mid, 1).First(&rechargeOrderData).Error
	if err != nil {
		define.Response.ResultFail(c, 10003, define.JsonDataX, "")
		return
	}
	list.Give = rechargeOrderData.Give
	list.MyRecharge = rechargeOrderData.Money
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    list,
	})
}

// 修改用户所在城市
func EditUserCity(c *gin.Context) {
	var jsonData models.MMember
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	var EditData = map[string]interface{}{
		"province":  jsonData.Province,
		"city":      jsonData.City,
		"area":      jsonData.Area,
		"address":   jsonData.Address,
		"latitude":  jsonData.Latitude,
		"longitude": jsonData.Longitude,
	}
	err = models.DB.Model(new(models.MMember)).Where("id=?", jsonData.ID).Updates(&EditData).Error
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    "成功",
	})
}

type SetUserData struct {
	UserName string `json:"user_name"`
	UserPic  string `json:"user_pic"`
	Phone    string `json:"phone"`
	Type     int    `json:"type"`
	UserId   int    `json:"user_id"`
	Sex      string `gorm:"type:varchar(255);" json:"sex"`      //性别
	Birthday string `gorm:"type:varchar(255);" json:"birthday"` //生日
	Levelid  int    `gorm:"type:int(11);" json:"levelid"`       //会员等级ID
}

// 修改用户头像
func SetUser(c *gin.Context) {
	//接收
	var jsonData SetUserData
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	var userData models.MMember
	userData.Headimg = jsonData.UserPic
	userData.Nickname = jsonData.UserName
	userData.Tel = jsonData.Phone
	userData.Sex = jsonData.Sex
	userData.Birthday = jsonData.Birthday
	userData.Levelid = jsonData.Levelid
	//判断是修改1头像、2昵称、3手机:
	err = models.DB.Model(new(models.MMember)).Where("id=?", jsonData.UserId).Updates(&userData).Error
	if err != nil {
		define.Response.ResultFail(c, 10004, err.Error(), "")
		return
	}
	//成功
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"data": "",
		"msg":  "成功",
	})
}

// 获取微信手机号返回参数
type WxPhoneReturn struct {
	Errcode   int       `json:"errcode"`
	Errmsg    string    `json:"errmsg"`
	PhoneInfo PhoneInfo `json:"phone_Info"`
}
type PhoneInfo struct {
	PhoneNumber     string    `json:"phoneNumber"`
	PurePhoneNumber string    `json:"purePhoneNumber"`
	CountryCode     string    `json:"countryCode"`
	Watermark       Watermark `json:"watermark"`
}
type Watermark struct {
	Timestamp int    `json:"timestamp"`
	Appid     string `json:"appid"`
}

// 获取微信手机号
func GetWXPhone(c *gin.Context) {
	var jsonData Login
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	//获取appid和密钥
	var appData models.AppCate
	err = models.DB.Model(new(models.AppCate)).Where("id=?", jsonData.AppId).First(&appData).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, err.Error(), "")
		return
	}
	//请求微信小程序接口调用凭据
	//拼接发起的url链接
	url := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"
	// 合成url, 这里的appId和secret是在微信公众平台上获取的
	url = fmt.Sprintf(url, appData.AppId, appData.AppSecret)
	// 创建http get请求
	resp, err := http.Get(url)
	if err != nil {
		define.Response.ResultFail(c, 10002, err.Error(), "")
		return
	}
	defer resp.Body.Close()
	// 解析http请求中body 数据到我们定义的结构体中
	wxResp := WXAccessToken{}
	decoder := json.NewDecoder(resp.Body)
	err = decoder.Decode(&wxResp)
	if err != nil {
		define.Response.ResultFail(c, 10003, err.Error(), "")
		return
	}
	//请求微信小程序接口调用凭据end

	//请求手机号
	postURL := "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s"
	// 合成url, 这里的appId和secret是在微信公众平台上获取的
	postURL = fmt.Sprintf(postURL, wxResp.AccessToken)
	//设置请求参数
	postBody, _ := json.Marshal(map[string]interface{}{
		"code": jsonData.Code,
	})
	responseBody := bytes.NewBuffer(postBody)
	respPost, err := http.Post(postURL, "application/json; charset=UTF-8", responseBody)
	if err != nil {
		define.Response.ResultFail(c, 10004, err.Error(), "")
		return
	}
	defer respPost.Body.Close()
	// 解析http请求中body 数据到我们定义的结构体中
	wxRespPost := WxPhoneReturn{}
	decoderPost := json.NewDecoder(respPost.Body)
	err = decoderPost.Decode(&wxRespPost)
	if err != nil {
		define.Response.ResultFail(c, 10005, err.Error(), "")
		return
	}
	//请求手机号结束
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "",
		"data": map[string]interface{}{
			"phoneNumber":     wxRespPost.PhoneInfo.PhoneNumber,
			"purePhoneNumber": wxRespPost.PhoneInfo.PurePhoneNumber,
		},
	})
}

// 查询获积分明细
func GetScoreShow(c *gin.Context) {
	var jsonData NewRecharData
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	var list []models.MMemberScorelog
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	tx := models.DB.Model(new(models.MMemberScorelog)).Where("aid=? AND mid=?", jsonData.Aid, jsonData.Mid)

	if jsonData.CreatedStart > 0 {
		tx = tx.Where("createtime>?", jsonData.CreatedStart/1000)
	}
	if jsonData.CreatedEnd > 0 {
		tx = tx.Where("createtime<?", jsonData.CreatedEnd/1000)
	}
	tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("id desc").Find(&list)
	if err != nil {
		define.Response.ResultFail(c, 10001, err.Error(), "")
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}
